package day19.zhiyou100;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

// 银行取钱
// 账户类
// 线程类
public class Demo01 {

    public static void main(String[] args) {
        // 创建共享的账户对象数据
        Account account = new Account("001", 1000);
        // Account account2 = new Account("002",2000);
        // 创建两个用户线程
        UserThread t1 = new UserThread(account, "用户A");
        t1.setMoney(500);
        UserThread t2 = new UserThread(account, "用户B");
        t2.setMoney(500);
        // 开启两个分线程
        t1.start();
        t2.start();
    }

}

// 定义一个用户线程类
class UserThread extends Thread {
    // 共用同一个账户
    private /*static*/ Account account;// 静态成员变量
    // 设置取钱的金额
    private double money;

    // 重写run方法
    @Override
    public void run() {
        account.withdraw(money);
        System.out.println(Thread.currentThread().getName() + "取钱后的余额为：" + account.getBalance());
    }

    public UserThread(Account account, String name) {
        super(name);
        this.account = account;
    }

    public Account getAccount() {
        return account;
    }

    public void setAccount(Account account) {
        this.account = account;
    }

    public double getMoney() {
        return money;
    }

    public void setMoney(double money) {
        this.money = money;
    }
}

// 定义一个账户类
class Account {
    // 卡号
    private String acc_ID;
    // 余额
    private double balance;
    final Object obj = new Object();// obj
    // 创建一个Lock锁
    Lock lock = new ReentrantLock();

    // 取钱的功能
    public void withdraw(double money) {
        System.out.println(Thread.currentThread().getName() + "---->当前余额为：" + balance);
        // 此时给下面的代码上锁
        lock.lock();

        if (money <= balance) {
            double before = balance;
            // 取钱后
            double after = before - money;
            // 发起取钱的动作 sleep(2000)
            balance = after;// 余额才会减少
        } else {
            System.out.println("余额不足！");
        }
        // 代表执行完毕后  手动释放锁
        lock.unlock();// 解锁
    }


    @Override
    public String toString() {
        return "Account{}";
    }

    public Account() {
    }

    public Account(String acc_ID, double balance) {
        this.acc_ID = acc_ID;
        this.balance = balance;
    }

    public String getAcc_ID() {
        return acc_ID;
    }

    public void setAcc_ID(String acc_ID) {
        this.acc_ID = acc_ID;
    }

    public double getBalance() {
        return balance;
    }

    public void setBalance(double balance) {
        this.balance = balance;
    }
}